package com.zhonglz.util.sign.ofd;

import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.Certificate;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1GeneralizedTime;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.DERIA5String;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERUTF8String;
import org.bouncycastle.asn1.gm.GMObjectIdentifiers;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.ofdrw.gm.ses.v1.SES_ESPictrueInfo;
import org.ofdrw.gm.ses.v1.SES_Header;
import org.ofdrw.gm.ses.v4.SES_CertList;
import org.ofdrw.gm.ses.v4.SES_ESPropertyInfo;
import org.ofdrw.gm.ses.v4.SES_SealInfo;
import org.ofdrw.gm.ses.v4.SESeal;

public class BuildSESeal {

	
	public  static SESeal sealBuild(Certificate userCert,byte[] picByte,PrivateKey privateKey) throws Exception {

		
	        ASN1EncodableVector v = new ASN1EncodableVector(1);
	        v.add(new DEROctetString(userCert.getEncoded()));
	        SES_Header header = new SES_Header(SES_Header.V4, new DERIA5String("OFDZ&LTest"));
	        Calendar now = Calendar.getInstance();
	        now.add(Calendar.YEAR, 2); //证书有效期2年
	        Date then = now.getTime();
	        SES_ESPropertyInfo propertyInfo = new SES_ESPropertyInfo()
	                .setType(new ASN1Integer(3))
	                .setName(new DERUTF8String("OFD Z&L 测试用印章"))
	                .setCertListType(SES_ESPropertyInfo.CertListType)
	                .setCertList(SES_CertList.getInstance(SES_ESPropertyInfo.CertListType, new DERSequence(v)))
	                .setCreateDate(new ASN1GeneralizedTime(new Date()))
	                .setValidStart(new ASN1GeneralizedTime(new Date()))
	                .setValidEnd(new ASN1GeneralizedTime(then));

	        SES_ESPictrueInfo pictrueInfo = new SES_ESPictrueInfo()
	                .setType("PNG")
	                .setData(picByte)
	                .setWidth(40) 
	                .setHeight(40);

	        SES_SealInfo sesSealInfo = new SES_SealInfo()
	                .setHeader(header)
	                .setEsID(new DERIA5String(UUID.randomUUID().toString().replace("-", "")))
	                .setProperty(propertyInfo)
	                .setPicture(pictrueInfo);

	        Signature sg = Signature.getInstance("SM3WithSM2", new BouncyCastleProvider());
	        sg.initSign(privateKey);
	        sg.update(sesSealInfo.getEncoded("DER"));
	        byte[] sigVal = sg.sign();

	       return new SESeal()
	                .seteSealInfo(sesSealInfo)
	                .setCert(userCert)
	                .setSignAlgID(GMObjectIdentifiers.sm2sign_with_sm3)
	                .setSignedValue(sigVal);
	        
	    }
}
